

const { getList, getDetail, newBlog, updateBlog, delBlog } = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')
// 拦截函数
const loginCheck = (req, userid) => {
    if (!req.session[userid].username) {
        return Promise.resolve(
            new ErrorModel('尚未登录')
        )
    }
}
const handleBlogRouter = (req, res, userid) => {

    const id = req.query.id
    // 获取博客列表
    if (req.method === 'GET' && req.path === '/api/blog/list') {
        const author = req.query.author || '';
        const keyword = req.query.keyword || '';
        const result = getList(author, keyword);


        return result.then(listData => {
            return new SuccessModel(listData)
        })
    }

    // 获取博客详情
    if (req.method === 'GET' && req.path === '/api/blog/detail') {
        const result = getDetail(id)
        return result.then(data => {
            return new SuccessModel(data)
        })
    }

    // 新建博客
    if (req.method === 'POST' && req.path === '/api/blog/new') {
        const loginCheckResult = loginCheck(req, userid)
        if (loginCheckResult) {
            // 未登录
            return loginCheckResult
        }
        req.body.author = req.session[userid].username
        const result = newBlog(req.body)
        return result.then(data => {
            return new SuccessModel(data)
        })
    }

    // 更新博客
    if (req.method === 'POST' && req.path === '/api/blog/update') {
        const loginCheckResult = loginCheck(req, userid)
        if (loginCheckResult) {
            // 未登录
            return loginCheckResult
        }
        const result = updateBlog(id, req.body)
        return result.then(val => {
            if (val) {
                return new SuccessModel()
            } else {
                return new ErrorModel('更新博客失败')
            }
        })
    }

    // 删除博客
    if (req.method === 'POST' && req.path === '/api/blog/delete') {
        const loginCheckResult = loginCheck(req, userid)
        if (loginCheckResult) {
            // 未登录
            return loginCheckResult
        }
        // author是当前的登录用户
        const author = req.session[userid].username;
        // const author = 'zhangsan'
        const result = delBlog(id, author)
        return result.then(val => {
            if (val) {
                return new SuccessModel('删除博客成功')
            } else {
                return new ErrorModel('删除博客失败')
            }
        })
    }
}

module.exports = handleBlogRouter